package sg.edu.nus.iss.billing.model.calculation;

import java.util.Date;

import sg.edu.nus.iss.billing.model.BaseModel;
import sg.edu.nus.iss.billing.model.bill.Bill;
import sg.edu.nus.iss.billing.model.bill.BillingPeriod;
import sg.edu.nus.iss.billing.model.charge.IChargable;
import sg.edu.nus.iss.billing.model.subscription.ISubscribable;
import sg.edu.nus.iss.billing.utils.DateHelper;
/**
 * 
 * @author Thurein, ZiFeng,YinNi
 *
 */
public class PerDay extends BaseModel implements IChargeMethod {

	private static final long serialVersionUID = -5499812009163015291L;

	@Override
	/**
	 * Get the charge amount by multiplying rate and no of days.
	 */
	public double calculate(IChargable fee, Bill chargingBill) {

		ISubscribable service = fee.getChargingService();
		double dailyRate =  PerDay.getDailyRate( fee.getRate().getAmount(),chargingBill.getBillingPeriod());
		long chargingDays =  PerDay.getNoOfChargingDays(service, chargingBill.getBillingPeriod()) ;
		double amount = dailyRate * chargingDays;
		return Math.round(amount * 100.00) / 100.00;// round decimal 2 point
	}

	protected static Date chargeEndDate(ISubscribable service, BillingPeriod billPeriod) {
		if (service.getDateTerminated() == null || service.getDateTerminated() == "")
			return billPeriod.getEndDate();
		Date serviceTerminatedDate = DateHelper.getDate(service.getDateTerminated(), "dd-MMM-yyyy");
		if (serviceTerminatedDate.before(billPeriod.getEndDate()))
			return serviceTerminatedDate;
		else
			return billPeriod.getEndDate();
	}

	protected static Date chargeStartDate(ISubscribable service, BillingPeriod billPeriod) {
		Date serviceCommercedDate = DateHelper.getDate(service.getDateCommenced(), "dd-MMM-yyyy");

		if (serviceCommercedDate.after(billPeriod.getStartDate()))
			return serviceCommercedDate;
		else
			return billPeriod.getStartDate();
	}

	public static long getNoOfChargingDays(ISubscribable service, BillingPeriod billPeriod) {
		Date chargeStartDate = chargeStartDate(service, billPeriod);
		Date chargeEndDate = chargeEndDate(service, billPeriod);

		return DateHelper.getDaysInBetween(chargeStartDate, chargeEndDate);
	}
	
	protected static double getDailyRate(double monthlyRate,BillingPeriod billPeriod){
		long numberOfDays = billPeriod.getNumberOfDays();
		return monthlyRate / numberOfDays;
		
	}

}
